<template>
	<view class="handle-page">
		<div class="statusBar" :style="{
			height: `${statusBarHeight}px`
		}"></div>
		<view class="title-box"
			:style="{ top: `${statusBarHeight}px`, height: `${topHeight}px`, padding: `${capsulePadding}px ${pagePadding}px` }">
			<view class="page-title">
				<i class="clearIcon" @click="goBack"></i>{{ pageTitle }}
			</view>
		</view>
		<div :style="{
			height: `${statusBarHeight + topHeight}px`
		}"></div>
		<view class="handle-page_container">
			<u-form :model="formData" :rules="rules" ref="uFormRef" label-position="top" label-width="auto">
				<!-- 接单 -->
				<u-form-item v-if="pageTitle === '接单'" label="备注" prop="remarks" required>
					<textarea :height="400" class="form_textarea" v-model="formData.remarks" />
				</u-form-item>
				<!-- 回单 -->
				<u-form-item v-if="pageTitle === '回单'" label="备注" prop="remarks" required>
					<textarea :height="400" class="form_textarea" v-model="formData.remarks" />
				</u-form-item>
				<!-- 到达现场 -->
				<u-form-item v-if="pageTitle === '到达现场'" label="备注" prop="remarks" required>
					<textarea :height="400" class="form_textarea" v-model="formData.remarks" />
				</u-form-item>
				<u-form-item v-if="pageTitle === '到达现场'" label="现场图片" prop="fileId" required>
					<!-- 上传区域 -->
					<u-upload :previewFullImage="true" @delete="handleDelete" :fileList="fileList" imageMode="aspectFit"
						name="image" :maxCount="1" @afterRead="handleAfterRead"></u-upload>
				</u-form-item>
				<!-- 巡查确认 -->
				<u-form-item v-if="pageTitle === '巡查确认'" label="详细情况说明" prop="remarks" required>
					<textarea :height="400" class="form_textarea" v-model="formData.remarks" />
				</u-form-item>
				<u-form-item v-if="pageTitle === '巡查确认'" label="巡查列表" required>
					<view class="card">
						<view class="table-box">
							<view class="table-h">
								<view class="table-h_cell">
									巡查事项
								</view>
								<view class="table-h_cell">
									巡查结果
								</view>
								<view class="table-h_cell">
									巡查图片
								</view>
							</view>
							<view style="height: 80rpx"></view>
							<!-- for循环加载列表数据 -->
							<view class="table-b" v-for="(item, index) in formData.alcmPatrolRecordDOList" :key="index">
								<view class="table-b_cell">
									{{ item.patrolItemName }}
								</view>
								<view class="table-b_cell">
									<view class="select_box" @click="toSelect(index)">
										{{ item.patrolCotentStr }}<u-icon name="arrow-down" class="u-m-l-10"
											color="#333" size="12"></u-icon>
									</view>
								</view>
								<view class="table-b_cell text-blue" @click="selectImg(index)">
									<span style="margin-right: 6px;" @click="selectImg(index)">上传</span>
									<span v-if="item.fileId" @click="previewImageFunc(item.fileId)">预览</span>
								</view>
							</view>
						</view>
					</view>
				</u-form-item>
				<!-- 异常确认 -->

				<u-form-item v-if="pageTitle === '异常确认'" label="故障原因" prop="remarks" required>
					<textarea :height="400" class="form_textarea" v-model="formData.remarks" />
				</u-form-item>
				<u-form-item v-if="pageTitle === '异常确认'" label="故障设备图片" prop="fileId" required>
					<!-- 上传区域 -->
					<u-upload :previewFullImage="true" @delete="handleDelete" :fileList="fileList" imageMode="aspectFit"
						name="image" :maxCount="1" @afterRead="handleAfterRead"></u-upload>

				</u-form-item>
				<!-- 运维确认 -->

				<u-form-item v-if="pageTitle === '运维确认'">
					<view class="user-info">
						<view class="user-info_item user-info_border">
							<view class="item_left">
								<image class="item_left-image" src="/static/images/worker/staff.png" mode=""></image>
								<view class="item_left-text">
									<text class="xinghao">*</text>
									<text class="text-name">维修厂商</text>
								</view>
							</view>
							<view class="item_right">
								{{ formData.repairFactory }}
							</view>
						</view>
						<view class="user-info_item user-info_border">
							<view class="item_left">
								<image class="item_left-image" src="/static/images/worker/staff.png" mode=""></image>
								<view class="item_left-text">
									<text class="xinghao">*</text>
									<text class="text-name">维修人员</text>
								</view>
							</view>
							<view class="item_right">
								{{ formData.repairPerson }}
							</view>
						</view>
						<view class="user-info_item">
							<view class="item_left">
								<image class="item_left-image" src="/static/images/worker/staff.png" mode=""></image>
								<view class="item_left-text">
									<text class="xinghao">*</text>
									<text class="text-name">厂家联系方式</text>
								</view>
							</view>
							<view class="item_right">
								{{ formData.factoryTel }}
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item v-if="pageTitle === '运维确认'" label="厂家诊断原因" prop="factoryReason" required>
					<textarea :height="400" class="form_textarea" v-model="formData.factoryReason" />
				</u-form-item>
				<u-form-item v-if="pageTitle === '运维确认'" label="故障处理结果" prop="remarks" required>
					<textarea :height="400" class="form_textarea" v-model="formData.remarks" />
				</u-form-item>

				<u-form-item label="故障处理图片" v-if="pageTitle === '运维确认'" prop="value2" required>
					<!-- 上传区域 -->
					<u-upload :previewFullImage="true" @delete="handleDelete" :fileList="fileList" imageMode="aspectFit"
						name="image" :maxCount="1" @afterRead="handleAfterRead"></u-upload>

				</u-form-item>
			</u-form>
			<view class="btns">
				<button class="btn-item ok" @click="handleSubmit">确定</button>
				<button class="btn-item close" @click="handleClose">取消</button>
			</view>
		</view>
		<u-picker :show="show" :columns="[columns]" @cancel="cancel" @confirm="confirm"></u-picker>
		<!-- 列表巡查结果选择框 -->
		<canvas canvas-id="myCanvas"
			:style="`opacity:0;z-index:-100;position:absolute; top:-1000px; left:-1000px; width:${curImageInfo.width}px; height:${curImageInfo.height}px;`"></canvas>
	</view>
</template>
<script setup>
import {
	getCurrentInstance, ref
} from "vue";
import config from '@/common/config'
const {
	proxy
} = getCurrentInstance();
// import { onLoad } from '@dcloudio/uni-app';
const statusBarHeight = ref(0); // 状态栏高度
const topHeight = ref(0); // 胶囊高度
const capsulePadding = ref(0);
const pagePadding = ref(0);
const pageTitle = ref('回单')
// 处理页面跳转
const goBack = (type) => {
	uni.navigateBack()
}
onMounted(() => {
	const systemInfo = uni.getSystemInfoSync();
	statusBarHeight.value = systemInfo.statusBarHeight; // 获取状态栏高度
	const res = uni.getMenuButtonBoundingClientRect();
	pagePadding.value = systemInfo.screenWidth - res.right
	topHeight.value = res.height + (res.top - statusBarHeight.value) * 2
	capsulePadding.value = res.top - statusBarHeight.value
});
const stepType = ref('')
onLoad((options) => {
	console.log(options); // 123 
	pageTitle.value = options.pageName
	workOrderNo.value = options.workOrderNo
	stepType.value = options.stepType
	getDetail()
});
const formData = ref({
	"factoryReason": '',
	"factoryTel": '',
	"fileId": '',
	"fileName": '',
	"remarks": '',
	"repairFactory": '',
	"repairPerson": '',
})
const rules = {}

const workOrderNo = ref('')
const getDetail = async () => {
	const res = await proxy.$http.POST('/aom/wechat/queryCommon', {
		obj: {
			workOrderNo: workOrderNo.value,
		},
		url: "queryWorkOrderStepDetailsListByWorkOrderNo"
	})
	if (res.code === '00000') {
		formData.value = res.data.find(item => item.stepType == stepType.value) || {}
		if (formData.value.fileId && formData.value.fileId != '') {
			fileList.value = [{
				url: config.baseURL + '/resources/download/downloadPhoto?uuid=' + formData.value.fileId + '&token=' + uni.getStorageSync('token')
			}]
		}
	}
}
const saveAlcmPatrolRecordDOList = async () => {
	const res = await proxy.$http.POST('/aom/wechat/queryCommon', {
		obj: formData.value.alcmPatrolRecordDOList,
		url: "batchUpdateAlcmPatrolRecord"
	})
	console.log('saveAlcmPatrolRecordDOList----->', res)
	if (res.code === '00000') {
	}
}
const handleSubmit = async () => {
	if (pageTitle.value === '巡查确认') {
		saveAlcmPatrolRecordDOList()
	}
	const stepTypeArr = [
		{
			type: '20',
			name: '派单'
		},
		{
			type: '30',
			name: '接单'
		},
		{
			type: '40',
			name: '到达现场'
		},
		{
			type: '50',
			name: '异常确认'
		},
		{
			type: '60',
			name: '抢修确认'
		},
		{
			type: '65',
			name: '运维确认'
		},
		{
			type: '70',
			name: '巡查确认'
		},
		{
			type: '80',
			name: '回单'
		},
		{
			type: '99',
			name: '归档'
		},
	]

	let stepTypeIndex = stepTypeArr.findIndex(item => formData.value.stepType === item.type)

	console.log("保存数据", formData.value)
	const res = await proxy.$http.POST('/aom/wechat/queryCommon', {
		obj: {
			"factoryReason": formData.value.factoryReason,
			"factoryTel": formData.value.factoryTel,
			"fileId": formData.value.fileId,
			"fileName": formData.value.fileName,
			"remarks": formData.value.remarks,
			"repairFactory": formData.value.repairFactory,
			"repairPerson": formData.value.repairPerson,
			"stepType": stepTypeArr[stepTypeIndex + 1].type,
			"workOrderNo": workOrderNo.value,
		},
		url: "saveWorkOrderStepDetails"
	})
	if (res.code === '00000') {
		uni.$emit('refreshList')
		uni.navigateBack({
			delta: 1
		})
	}
	console.log(formData.value)
}
const handleClose = () => {
	// init退出
	goBack()
}
const curIndex = ref(0)
// 列表选择
const toSelect = (index) => {
	curIndex.value = index
	show.value = true
}

// 图片上传压缩水印
const fileList = ref([]);

const handleDelete = (index) => {
	fileList.value.splice(index, 1);
};
const handleAfterRead = async (event) => {
	uploadType.value = 'form'
	const file = event.file;
	console.log('file--->', file)
	compressImage(file.url, file.name)
};

const uploadType = ref('') // table / form
const curImageInfo = ref({})
const selectImg = (index) => {
	curIndex.value = index
	uploadType.value = 'table'
	uni.chooseImage({
		count: 1, // 最多选择1张图片
		sizeType: ['compressed'], // 限制选择压缩图
		sourceType: ['album', 'camera'],
		success: async function (res) {
			console.log('res------->', res)
			const tempFilePaths = res.tempFilePaths; // 获取压缩后的图片临时路径
			// 1. 添加水印
			console.log('tempFilePaths[0]--------->', tempFilePaths[0])
			compressImage(tempFilePaths[0], '')
		},
		fail: function (err) {
			console.error('选择图片失败', err);
		}
	});
}
function compressImage(tempFilePath, tempFileName) {
	wx.compressImage({
		src: tempFilePath, // 图片路径
		quality: 50, // 压缩质量
		success: async (res) => {
			console.log('压缩后的图片路径：', res.tempFilePath);
			addWatermark(res.tempFilePath, tempFileName)
		}
	})
}
function updateTime() {
	const now = new Date();
	const year = now.getFullYear();
	const month = (now.getMonth() + 1).toString().padStart(2, '0');
	const day = now.getDate().toString().padStart(2, '0');
	const hours = now.getHours().toString().padStart(2, '0');
	const minutes = now.getMinutes().toString().padStart(2, '0');
	const seconds = now.getSeconds().toString().padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
// 加水印
async function addWatermark(imagePath, imageName) {
	try {
		// 1. 获取图片信息
		const imageInfo = await new Promise((resolve, reject) => {
			uni.getImageInfo({
				src: imagePath,
				success: resolve,
				fail: reject
			});
		});

		// 3. 准备水印文本数组    与甲方核对水印具体样式
		uni.chooseLocation({
			success: function (res) {
				console.log('位置名称：' + res.name);
				console.log('详细地址：' + res.address);
				console.log('纬度：' + res.latitude);
				console.log('经度：' + res.longitude);
				const watermarkTexts = [`经度：${res.longitude}`, `纬度：${res.latitude}`, `地址：${res.address}`, `时间：${updateTime()}`];

				// 4. 创建 Canvas 上下文
				curImageInfo.value = imageInfo
				const ctx = uni.createCanvasContext('myCanvas', this); // 假设canvas的canvas-id为'myCanvas'
				const canvasWidth = imageInfo.width;
				const canvasHeight = imageInfo.height;

				// 5. 绘制原图
				ctx.drawImage(imagePath, 0, 0, canvasWidth, canvasHeight);

				// 6. 设置水印样式
				const fontSize = Math.max(canvasWidth / 30, 14); // 动态字体大小
				ctx.setFontSize(fontSize);
				ctx.setFillStyle('rgba(255, 255, 255, 0.7)'); // 白色半透明
				ctx.setTextAlign('left');

				// 7. 计算水印背景区域
				const textHeight = fontSize * 1.2;
				const padding = 10;
				const backgroundHeight = textHeight * watermarkTexts.length + padding * 2;
				const backgroundY = canvasHeight - backgroundHeight - 20; // 距底部20px

				// 绘制半透明背景，提升水印可读性
				ctx.setFillStyle('rgba(0, 0, 0, 0.4)');
				ctx.fillRect(0, backgroundY, canvasWidth, backgroundHeight);

				// 8. 绘制水印文本 (每行)
				ctx.setFillStyle('rgba(255, 255, 255, 0.9)'); // 恢复文字颜色
				watermarkTexts.forEach((text, index) => {
					const y = backgroundY + padding + textHeight * (index + 1);
					ctx.fillText(text, 20, y); // 距左边20px
				});

				// 9. 将Canvas内容绘制出来并生成新图片
				ctx.draw(false, () => {
					setTimeout(() => { // 确保上一步绘制完成
						uni.canvasToTempFilePath({
							canvasId: 'myCanvas',
							success: (res) => {
								const watermarkedImagePath = res.tempFilePath;
								console.log('调用上传图片接口')
								// 这里可以预览或上传 watermarkedImagePath
								uploadImage(watermarkedImagePath, imageName);
							},
							fail: (err) => {
								console.error('Canvas导出图片失败', err);
							}
						});
					}, 100);
				});
			},
			fail: function (err) {
				console.log('选择位置失败：', err);
			}
		});

	} catch (error) {
		console.error('添加水印过程出错', error);
	}
}
// 预览
function previewImageFunc(fileId) {
	let imgUrl = config.baseURL + '/resources/download/downloadPhoto?uuid=' + fileId + '&token=' + uni.getStorageSync('token')
	uni.previewImage({
		current: imgUrl,
		urls: [imgUrl],
	});
}
// 上传
async function uploadImage(tempFilePath, tempFileName) {
	console.log('调用上传图片接口参数:' + tempFilePath + ' -- ' + tempFileName)
	uni.uploadFile({
		url: config.baseURL + '/resources/upload/uploadPhoto',
		filePath: tempFilePath,
		name: 'file',
		header: {
			// 'token': 'F0B3BA0E8F25BEECF03B28DAF8A62842',
			'token': uni.getStorageSync('token'),
			organizationId: 1005,
			fileType: '04'
		},
		formData: {},
		success: function (up) {
			console.log('调用上传图片接口成功up', up)
			var data = JSON.parse(up.data)
			console.log('调用上传图片接口成功up.data', data)
			if (uploadType.value === 'table') {
				formData.value.alcmPatrolRecordDOList[curIndex.value].fileId = data.data.uuid
			} else if (uploadType.value === 'form') {
				formData.value.fileId = data.data.uuid
				formData.value.fileName = data.data.photoName
				fileList.value = [{
					url: config.baseURL + '/resources/download/downloadPhoto?uuid=' + formData.value.fileId + '&token=' + uni.getStorageSync('token')
				}]
			}
		},
		fail: function (up) {
			console.log('调用上传图片接口失败，', up)
		}
	})
}

const show = ref(false)
const columns = ['正常', '异常']
const cancel = () => {
	show.value = false
}
const confirm = (e) => {
	console.log('confirm', e.value[0])
	formData.value.alcmPatrolRecordDOList[curIndex.value].patrolCotentStr = e.value[0]
	formData.value.alcmPatrolRecordDOList[curIndex.value].patrolCotent = e.value[0] === '正常' ? '0' : '1'
	show.value = false
}



</script>

<style scoped lang="scss">
:deep(.u-form-item__body__left__content__required) {
	left: 0px !important;
}

:deep(.u-form-item__body__left__content) {}

:deep(.u-form-item__body__left__content__label) {
	color: rgb(102, 102, 102) !important;
	position: relative !important;
	left: 14px !important;
}

:deep(.u-upload__button) {
	background-color: #fff;
}

.form_textarea {
	width: 100%;
	background-color: #fff;
	border-radius: 15rpx;
	padding: 15px;
}

.handle-page {
	background: #f1f1f1;
	min-height: 100vh;

	&_container {
		padding: 0 20rpx;
	}
}

.btns {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 0;

	.btn-item {
		width: calc(50% - 40rpx);
		margin: 0;
		border-radius: 23px;
	}

	.ok {
		background-color: $uni-color-project;
		color: #fff;
	}

	.close {
		background-color: #f1f1f1;
		color: $uni-color-project;
		border: 1px solid $uni-color-project;
	}
}

.card {
	width: 100%;
	padding: 40rpx;
	border-radius: 20rpx;
	background-color: #fff;
}

.table-box {
	width: 100%;
	// height: 400rpx;
	border-radius: 40rpx;
	overflow-y: auto;
	position: relative;

	.table-b {

		width: 100%;
		height: 80rpx;
		display: flex;

		// 奇数行样式
		&:nth-child(odd) {
			background-color: rgba(47, 154, 255, 0.07);
		}

		// 偶数行样式
		&:nth-child(even) {
			background-color: #fff;
		}

		&_cell {
			width: calc(33.33333%);
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
}

.table-h {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 80rpx;
	background-color: rgba(47, 154, 255, 0.2);
	display: flex;

	&_cell {
		width: calc(33.33333%);
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: $uni-color-project;
		font-size: 32rpx;
	}
}

.select_box {
	display: flex;
	padding: 3px 7px;
	align-items: flex-end;
	border: 2px solid #ececec;
	border-radius: 3px;
}

.user-info {
	background-color: #fff;
	padding: 10px 40rpx;
	border-radius: 20rpx;
	width: 100%;

	&_border {
		border-bottom: 1.5px solid #f1f1f1;
	}

	&_item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 0px 5px;

		.item_left {
			display: flex;
			align-items: center;

			&-image {
				height: 60rpx;
				width: 60rpx;
				margin-right: 20rpx;
			}

			&-text {
				font-size: 26rpx;

				.xinghao {
					color: red !important;
				}

				.text-name {
					color: rgb(153, 153, 153)
				}
			}
		}

		.item_right {
			// display: flex;
			// align-items: center;
		}
	}
}
</style>
